<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Forms\GiftForm;
use App\Modules\Package\Models\Gift;
use App\Modules\Package\Models\GiftScope;
use App\Modules\Package\Models\GoodPackage;
use App\Modules\Package\Models\PackageAttrValue;
use Illuminate\Http\Request;
use App\Modules\Shop\Shop;
use Illuminate\Support\Facades\Auth;
use App\Modules\User\Models\Admin;

class GiftController extends Controller
{

    /**
     * 搜索门店
     */
    public function searchShops(Request $request){
        
        $this->checkAuth('staff_gift', 'gift');
        $term = $request->input('term');
        $is_photography = 1;//婚纱门店
        $query = Shop::query();
        $query->where('status', 'open');
        if (!empty($term)) {
            $query->where('name', 'like', "%".$term."%");
        }

        if (!empty($is_photography)) {
            $query->where('is_photography', $is_photography);
        }

        if (isset($this->authUser->is_merchant_staff) && $this->authUser->is_merchant_staff == Admin::MERCHANT_AUTH) {
            $query->whereIn('id', json_decode($this->authUser->shop_id, true));
        }

        $re = $query
            ->get()
            ->pluck('name', 'id')
            ->all();

        $re[0] = '全部门店';
        return $re;
    }

    public function index(Request $request)
    {
        $this->checkAuth('staff_gift', 'gift');

        $title    = $request->input('title');
        $shopId   = $request->input('shop_id', '');
        $shopName = $shopId ? Shop::query()->where('id', $shopId)->first('name')->name : '全部门店';

        $query = Gift::query()
            ->leftJoin('shops', 'shops.id', '=', 'gifts.shop_id')
            ->orderBy('gifts.created_at', 'desc');

        if (isset($this->authUser->is_merchant_staff) && $this->authUser->is_merchant_staff == Admin::MERCHANT_AUTH) {
            $query->whereIn('gifts.shop_id', json_decode($this->authUser->shop_id, true));
        }
        
        if ($title != '') {
            $query->where('gifts.title', 'like', "%" . $title . "%");
        }

        if ($shopId) {
            $query->where('gifts.shop_id', $shopId);
        }

        $data = $query
                ->select('gifts.*', 'shops.name as shop_name')
                ->paginate(30);

        foreach ($data as $item) {
            $content = "";
            foreach ($item->content as $value) {
                $content .= ($value['name']??"")." *{$value['number']}<br />";
            }
            $item->content = $content;
        }
        $data->content = implode( '\n', array_column($data->pluck('content')->all(), 'name'));

        return view('gift.index', compact('data', 'title', 'shopId', 'shopName'));
    }

    public function create(Request $request)
    {
        $this->checkAuth('staff_gift-add','gift-add');

        $all = PackageAttrValue::query()
            ->get()
            ->pluck('value', 'id')
            ->all();
        $form = $this->form(GiftForm::class, [
            'url' => route('admin.gift.store'),
            'method' => 'POST',
        ], [
            'all' => $all,
        ]);
        return view('gift.form', compact('form'));
    }

    public function store()
    {
        $this->checkAuth('staff_gift-add', 'gift-add');
        $form = $this->form(GiftForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $number = [];

        foreach ($data['content'] as $value) {
            $number[$value['id']] = $value['number'];
        }
        $data['content'] = PackageAttrValue::query()
            ->whereIn('id', array_column($data['content'], 'id'))
            ->get()
            ->map(function ($item) use ($number) {
                return [
                    'id' => $item->id,
                    'name' => $item->value,
                    'number' => $number[$item->id]
                ];
            });
        $data['admin_id'] = Auth::user()->id;
        $gift = Gift::query()
            ->create($data);
        if (!empty($data['package_id'])) {
            foreach ($data['package_id'] as $value) {
                GiftScope::query()
                    ->create([
                        'package_id' => $value,
                        'gift_id' => $gift->id
                    ]);
            }
        }
        return redirect()->route('admin.gift.index');
    }

    public function edit(Gift $gift)
    {
        $this->checkAuth('staff_gift-edit', 'gift-edit');
        $scope = GiftScope::query()
            ->where('gift_id', $gift->id)
            ->get();
        $gift->package_id = $scope->pluck('package_id');
        $package = GoodPackage::query()->whereIn('id', $scope->pluck('package_id')->all())->get();
        $all = PackageAttrValue::query()
            ->get()
            ->pluck('value', 'id')
            ->all();
        $content = [];
        foreach ($gift->content as $item) {
            $content[$item['id']] = $item['name'];
        }

        // 获取门店
        $shops = Shop::query()->get(['id', 'name']);

        $form = $this->form(GiftForm::class, [
            'url' => route('admin.gift.update', ['gift' => $gift]),
            'method' => 'PUT',
            'model' => $gift,
        ], [
            'package' => $package->pluck('name', 'id')->all(),
            'all' => $all,
            'shops' => $shops->pluck('name', 'id')->all()
        ]);
        return view('gift.form', compact('form'));
    }

    public function update(Gift $gift)
    {
        $this->checkAuth('staff_gift-edit', 'gift-edit');
        $form = $this->form(GiftForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();

        $old = GiftScope::query()
            ->where('gift_id', $gift->id)
            ->get()
            ->pluck('package_id')
            ->all();
        $add = array_diff($data['package_id'], $old);
        $del = array_diff($old, $data['package_id']);
        foreach ($add as $value) {
            GiftScope::query()
                ->create([
                    'package_id' => $value,
                    'gift_id' => $gift->id,
                ]);
        }
        foreach ($del as $value) {
            GiftScope::query()
                ->where('package_id', $value)
                ->where('gift_id', $gift->id)
                ->delete();
        }
        unset($data['package_id']);
        foreach ($data['content'] as $value) {
            $number[$value['id']] = $value['number'];
        }
        $data['content'] = PackageAttrValue::query()
            ->whereIn('id', array_column($data['content'], 'id'))
            ->get()
            ->map(function ($item) use ($number) {
                return [
                    'id' => $item->id,
                    'name' => $item->value,
                    'number' => $number[$item->id]
                ];
            });
        $data['admin_id'] = Auth::user()->id;
        $gift->update($data);
        return redirect()->route("admin.gift.index");
    }

    public function destroy(Gift $gift)
    {
        $this->checkAuth('staff_gift-delete', 'gift-delete');

        $gift->delete();
        GiftScope::query()
            ->where('gift_id', $gift->id)
            ->delete();
        return redirect()->route('admin.gift.index');
    }
}
